<template>
	<!-- 点击扫描套餐卡二维码 -->
	<view>
    <view class="text-primary text-sm padding-lr">{{$t('JLink.packageCard.QRText')}}</view>
    <couponsQRCode @click="openQRScanClick"></couponsQRCode>
    <view class="cu-card" style="margin-top:100upx">
      <view class="cu-item" style="border: 2upx solid #efeded">
        <view class="cu-form-group" style="min-height: 84upx;">
          <input class="text-align:left" placeholder-class="text-df text-gray" :placeholder="$t('JLink.placeholder.packageCard')" name="contact"
                 v-model.trim="cardVal" @input="cardInputVal" @blur="pageScrollTo" />
        </view>
      </view>
    </view>
    <!-- 使用规则说明 -->
    <view class="margin-lr text-gray text-sm" @tap="handleRule">*{{$t('JLink.packageCard.ruleText')}}</view>
    <!-- 设备列表 -->
    <device-radios
      :devIdRadioValue="devIdRadioValue"
      :chnIdRadioValue="chnIdRadioValue"
      @updateDevIdRadioValue="updateDevIdRadioValue"
      @updateChnIdRadioValue="updateChnIdRadioValue"
      :list="deviceList"
      :title="$t('JLink.packageCard.selectDevId')"
      @IconChange="IconChange"
    >
    </device-radios>
    <!-- 底部button -->
    <view style="height:200rpx"></view>
    <j-foot style="background-color: #F8F8F8;">
      <view class="flex flex-direction padding" style="width:100%;">
        <button :disabled="cardVal==''|| submitLoading || devIdRadioValue==''" :loading="submitLoading" class="KCARD cu-btn block bg-white text-primary margin-tb-sm lg radius" style="border: 2upx solid #efeded" @tap="qrCardQuery">{{$t('JLink.publicText.submit')}}</button>
      </view>
    </j-foot>
    <!-- 使用规则说明 -->
    <basis-modal #default :modalName="modalName" @updateModalName="updateModalName" :title="$t('JLink.packageCard.ruleText')">
      <view class="padding-xl">
        <view class="text-left" style="padding-top:10upx" :class="item.class? item.class:''" v-for="(item,i) in ruleList" :key="i">{{item.title}}</view>
      </view>
    </basis-modal>
    <!-- 查询到的套餐信息 -->
    <cardNotesModal ref="cardNotesModalRef" :modalName="modalName" @updateModalName="updateModalName" :message="cardNotes" @cardUseSubmit="cardUseSubmit"></cardNotesModal>
    <!-- 成功使用套餐卡，是否查看订单详情 弹框 -->
    <successUesModal :modalName="modalName" @updateModalName="updateModalName"></successUesModal>
    <!-- 错误提示 模态框 -->
    <error-modal :modalName="modalName" :errCode="errCode" @changeModalName="updateModalName"></error-modal>
  </view>
</template>

<script>
import logins from '@/utils/loginApi.js'
import { packageCardQuery, packageCardApply, appletDeviceList } from '@/API/api.js'
import getDeviceChannel from './js/getDeviceChannel.js'
import couponsQRCode from "@/components/uni-QRCode/index.vue"
import deviceRadios from './module/packageCard/deviceRadios.vue'
import cardNotesModal from './module/packageCard/cardNotesModal.vue'
import successUesModal from './module/packageCard/successUesModal.vue'
import errorModal from "../../components/modal/error.vue"
import basisModal from "../../components/modal/basis.vue"

const {handleLogin,httpReturn} = logins(); //登录
const {deviceMessage} = getDeviceChannel();

export default {
  components: {
    couponsQRCode,
    deviceRadios,
    cardNotesModal,
    successUesModal,
    errorModal,
    basisModal
  },
  props:{
  },
  data() {
    return {
      cardVal: '', //输入的套餐卡
      deviceList: [], //设备列表
      devIdRadioValue:'',//选择的设备id
      chnIdRadioValue:'',//选择的通道号
      modalName:'',
      ruleList:[],
      submitLoading:false,
      errCode:'',//错误提示
      cardNotes:{},//查询的套餐卡信息
    }
  },
  mounted() {
    this.handleMethod();
  },
  onLoad(opt) {
    const { cardVal } = opt;
    this.cardVal= cardVal ? cardVal : '';
  },
  onUnload() {
    uni.removeStorageSync('packageCardSelect')
  },
  methods: {
    handleMethod () {
      this.cardVal=='';
      this.submitLoading = false;
      this.ruleList = [
        {title:this.$t('JLink.packageCard.rule.one')},
        {title:this.$t('JLink.packageCard.rule.two')},
        {title:this.$t('JLink.packageCard.rule.three'),class:'text-red'}
      ]
      this.handleGetAppDevice()
    },
    handleGetAppDevice () {
      this.deviceList = [];
      let header = {
        Authorization:uni.getStorageSync('accessToken'),
        appKey:getApp().globalData.appConfig.xm_appKey
      }
      appletDeviceList(header).then(result=>{
        let data= result.data||[]
        let devList = []
        if(data&&data.length){
          data.forEach(z=>{
            devList.push({devId:z.deviceNo,devName:z.deviceName,devType:z.pid,devState:0})
          })
        }
        this.devIdRadioValue = uni.getStorageSync('packageCardSelect') ? uni.getStorageSync('packageCardSelect') : '';
        this.chnIdRadioValue = uni.getStorageSync('packageCardSelChannel') ? uni.getStorageSync('packageCardSelChannel') : '-1';
        deviceMessage(devList,this.devIdRadioValue,(ar)=>{
          this.deviceList.push(ar);
        })//能力集获取设备通道
      });
    },
    cardInputVal (e) {
      this.cardVal = e.detail.value;
    },
    pageScrollTo () {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });
    },
    updateDevIdRadioValue(value) {
      this.devIdRadioValue = value
    },
    updateChnIdRadioValue(value) {
      this.chnIdRadioValue = value
    },
    // 多通道选择
    IconChange (item) {
      const {devId} = item;
      this.deviceList.forEach(z=>{
        if(z.devId===devId){
          z.icon = z.icon==='fold' ? 'unfold':'fold';
        }else{
          z.icon='fold';
        }
      })
    },
    // 点击二维码唤醒扫描
    openQRScanClick () {
      this.cardVal = '';
      // getOpenQRScanMessage()
      let _this = this
      wx.scanCode({
        needResult: 1,
        success (res) {
          _this.cardVal = res.result;
          console.log('res.result', res.result);
        },
        fail (res) {
          _this.cardVal = '';
        },
      })
    },
    // 查看规则
    handleRule () {
      this.modalName='basisModal';
    },
    // 套餐卡二维码查询
    qrCardQuery (){
      handleLogin(()=>{
        this.submitLoading = true;
        let params = {
          qr:this.cardVal,//二维码
          deviceId:this.devIdRadioValue,
          channel:this.chnIdRadioValue
        }
        packageCardQuery(params).then(res=>{
          this.submitLoading = false;
          httpReturn(res,(data)=>{
            this.cardNotes = data;//返回查询的信息
            this.modalName = 'cardNotesModal'//查看套餐卡信息
          },(code) =>{
            this.modalName = 'errorMessage';
            // this.errCode = code
            if (code == '-91000') {
              this.errCode = 'packageCardFormatError'
            } else {
              this.errCode = code
            }
          })
        }).catch(()=>{
          this.submitLoading = false;
        })
      })
    },
    // 套餐卡使用
    cardUseSubmit () {
      this.$refs.cardNotesModalRef.loading = true;
      let params = {
        qr:this.cardVal,//二维码
        deviceId:this.devIdRadioValue,
        channel:this.chnIdRadioValue
      }
      packageCardApply(params).then(res=>{
        this.$refs.cardNotesModalRef.loading = false;
        httpReturn(res,(data)=>{
          if(data){
            this.modalName = 'successUesModal'
          }
        },(code) =>{
          this.modalName = 'errorMessage';
          this.errCode = code
        })
      }).catch(()=>{
        this.$refs.cardNotesModalRef.loading = false;
      })
    },
    updateModalName (value) {
      this.modalName = value
    }
  }
}
</script>

<style lang="less" scope>
@import '@/common/style/main.css';
</style>
